package com.heima.wemedia.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.common.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Value("${file.oss.web-site}")
    String website;
@Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * 自动审核方法
     *
     * @param wmNewsId
     */
    @Override
    public void autoScanWmNews(Integer wmNewsId) {
        log.info("接受到的文章自动审核消息 消费的内容为==》{}", wmNewsId);
        //1.检查参数
        if (wmNewsId == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wmNewsMapper.selectById(wmNewsId);
        log.error("文章自动审核失败  未查询到相关文章===》", wmNewsId);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "为查询到文章信息");
        }
        //2。判断文章状态是否是待审核状态
        Short status = wmNews.getStatus();
        log.error("文章自动审核失败  文章状态不是待审核状态，无法进行审核操作===》{}", wmNewsId);
        if (status.shortValue() == WmNews.Status.SUBMIT.getCode()) ;
        //3.抽出文章中所有内容和所有文本图片url集合
        Map<String, Object> contentAndImageResult = handleTextAndImages(wmNews);

        //TODO  3.1 DFA敏感词审核  失败   修改文章状态
        boolean isSensivice = handleSensitive((String) contentAndImageResult.get("content"), wmNews);
        if (!isSensivice) return;
        log.info("文章自动审核  敏感词审核通过==》{}", wmNewsId);
        //TODO 3.2阿里云文本审核  失败  状态2  不确定  状态3
        boolean isTextScan = handleTextScan((String) contentAndImageResult.get("content"), wmNews);
        if (!isTextScan) return;
        log.info("文章自动审核  文本审核通过==》{}", wmNewsId);
        //TODO 3.3阿里云的图片审核 失败  状态2  不确定  状态3
        boolean isImageSacn = handleImageScan((List<String>) contentAndImageResult.get("images"), wmNews);
        if (!isImageSacn) return;
        log.info("文章自动审核  图片审核通过==》{}", wmNewsId);
        //TODO 3.4. 文章状态改为8  审核通过
        updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "审核通过");
        //TODO 5. 通知定时发布文章
        //5. 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
               /* new MessagePostProcessor() {
                    *//*
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        //对消息后置处理  设置消息请求头  x-delay 延时消息
                        message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                        return message;
                    }
                }
        );*/



    }


    /**
     * 阿里云审核图片
     *
     * @param images
     * @param wmNews
     * @return
     */
    @Autowired
    GreenImageScan greenImageScan;

    /**
     * 阿里云图片审核
     *
     * @param images 待审核的图片列表
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片中有违规内容，审核失败");
                    flag = false;
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片中有不确定内容，转为人工审核");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云图片审核出现异常 , 原因:{}", e.getMessage());
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云内容服务异常，转为人工审核");
            flag = false;
        }
        return flag;
    }

    /**
     * 基于DFA 检测内容是否包含敏感词
     * 成功返回true，失败返回false
     *
     * @param content
     * @param wmNews
     * @return
     */
    @Autowired
    AdminFeign adminFeign;

    private boolean handleSensitive(String content, WmNews wmNews) {

//1.查询数据库中敏感词
        ResponseResult<List<String>> allSensitivesResult = adminFeign.selectAllChannel();
        if (allSensitivesResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);//504远程调用失败
        }
        List<String> data = allSensitivesResult.getData();
        //2。DFA工具类初始化DFA模型
        SensitiveWordUtil.initMap(data);
        //3。使用DFA算法检测敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        //更具审核结果，将文章状态改为2
        if (map != null && map.size() > 0) {//有敏感词
            //修改状态为2
            updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文本的内容包含敏感词:" + map.toString());
            return false;
        }

        return true;
    }

    /**
     * 阿里云文本审核
     * block  状态2
     * review  状态3
     *
     * @param content
     * @param wmNews
     * @return
     */
    @Autowired
    GreenTextScan greenTextScan;

    /*private boolean handleTextScan(String content, WmNews wmNews) throws Exception {
        boolean flag = true;
        try {

            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "review":
                    updateWmnews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文本中不确定，需要人工审核");
                    flag = false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            updateWmnews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "调用阿里云接口失败，转为人工接口");

            flag = false;
        }
        return flag;
    }*/
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文本中有违规内容，审核失败");
                    flag = false;
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文本中有不确定内容，转为人工审核");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();

            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云内容服务异常，转为人工审核");
            flag = false;
        }
        return flag;
    }


    /**
     * 修改文章状态
     * 文章
     * 状态
     * 原因
     */
    private void updateWmNews(WmNews wmNews, Short code, String s) {

        wmNews.setReason(s);//原因
        wmNews.setStatus(code);//状态
        wmNewsMapper.updateById(wmNews);

    }


    /**
     * 抽取文章中 所有文本内容  和所有图片url
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //[{type:text,value:文本},{type:image,value:url},{},{}]


        String contentJson = wmNews.getContent();

        List<Map> contentMap = JSONArray.parseArray(contentJson, Map.class);
        //1。抽取所有文本内容
        StringBuilder content = new StringBuilder(wmNews.getTitle());
        //1。1遍历contentMap，找到type=text  遍历所有内容   拼接到content字符串上
        contentMap.stream()
                .filter(map -> "text".equals(map.get("type")))
                .map(o -> (String) o.get("value"))
                .forEach((text) -> content.append("_hmtt_" + text));//分隔符


        //2。图片url
        List<String> imageList = contentMap.stream().filter(map -> "image".equals(map.get("type")))
                .map(o -> (String) o.get("value")).collect(Collectors.toList());
        //url,url2,url3
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            //url,url2,url3
            List<String> urls = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> website + url)
                    .collect(Collectors.toList());
            imageList.addAll(urls);
        }
        //去重，防止封面重复
        imageList = imageList.stream().distinct().collect(Collectors.toList());

        HashMap<String, Object> result = new HashMap<>();
        result.put("content", content.toString());
        result.put("images", imageList);


        return result;
    }


}
